const express = require('express')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const rongSms = require('rongSms');
const router = express.Router()
const User = require('../../model/User')
const Comment = require('../../model/Comment')
const sms_util = require('../../util/sms_util')
const users = {}

//添加用户
router.post('/add', (req, res) => {
  User.findOne({username: req.body.username})
    .then(user => {
      if (user) {
        return res.status(400).json({user: '该用户名已存在'})
      } else {
        const user_info = req.body
        //密码加密
        bcrypt.genSalt(10, function (err, salt) {
          bcrypt.hash(user_info.password, salt, (err, hash) => {
            if (err) throw err
            user_info.password = hash
            new User(user_info).save().then(user => {
              res.json(user)
            })
          })
        })
      }
    })
})

//编辑用户
router.post('/update/:id', (req, res) => {
  User.findOneAndUpdate({
    _id: req.params.id
  }, {
    $set: req.body
  }, {
    new: true
  }).then(user => res.json(user))
})

// 删除用户
router.delete('/delete/:id', (req, res) => {
  const user = User.findOneAndRemove({
    _id: req.params.id
  }).then(user => '删除成功')
    .catch(err => '删除失败')
  const comment = Comment.remove({
    uid: req.params.id
  }).then(comment => '删除成功')
    .catch(err => '删除失败')
  Promise.all([user, comment])
    .then(result => res.json('删除成功'))
    .catch(err => res.status(400).json('删除失败'))
})

//查询用户
router.get('/', (req, res) => {
  User.find()
    .then(user => {
      if (!user) {
        return res.status(404).json('没有任何内容')
      }
      res.json(user)
    })
    .catch(err => res.status(404).json(err))
})

//查询单个用户
router.get('/singleUser/:id', (req, res) => {
  User.findOne({
    _id: req.params.id
  })
    .then(user => {
      if (!user) {
        return res.status(404).json('没有任何内容')
      }
      res.json(user)
    })
    .catch(err => res.status(404).json(err))
})

//登录
router.post('/login', (req, res) => {
  const username = req.body.username
  const password = req.body.password
  User.findOne({username})
    .then(user => {
      if (!user) {
        return res.status(404).json({username: '用户名不存在'})
      }
      //验证密码
      bcrypt.compare(password, user.password)
        .then(isMath => {
          if (isMath) {
            const rule = {id: user._id, name: username.username}
            jwt.sign(rule, 'secret', {expiresIn: 3600}, (err, token) => {
              if (err) throw err
              const userData = {
                success: true,
                token: 'user' + token,
                user
              }
              if (user.identity === '管理员') {
                userData.adminToken = 'admin' + token
              }
              res.json(userData)
            })
          } else {
            return res.status(400).json({password: '密码错误'})
          }
        })
    })
})

// 忘记密码
router.post('/forget', async (req, res) => {
  let password = req.body.password
  const username = await User.find({username: req.body.username})
  if (username.length === 0) {
    return res.status(400).json('用户名不存在')
  }
  res.json({code:123456})
  //密码加密
  bcrypt.genSalt(10, function (err, salt) {
    bcrypt.hash(password, salt, (err, hash) => {
      if (err) throw err
      password = hash
      User.findOneAndUpdate({
        username: req.body.username
      }, {
        $set: {
          password: password
        }
      }, {
        new: true
      }).then(user => res.json(user))
    })
  })
})

//发送验证码
router.get('/sendcode', (req, res) => {
//1. 获取请求参数数据
  var phone = req.query.phone
  // 2. 处理数据
  // 生成验证码(6位随机数)
  var code = sms_util.randomCode(6)
  //发送给指定的手机号
  console.log(`向${phone}发送验证码短信: ${code}`)
  sms_util.sendCode(phone, code, function (success) {//success表示是否成功
    if (success) {
      users[phone] = code
      console.log('保存验证码: ', phone, code)
      res.json({code})
    } else {
      //3. 返回响应数据
      res.status(400).json({msg: '短信验证码发送失败'})
    }
  })
})

module.exports = router